package cn.skillith.showcompanybackend.controller;

import cn.skillith.showcompanybackend.entity.ContactMessage;
import cn.skillith.showcompanybackend.service.ContactService;
import cn.skillith.showcompanybackend.service.SecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = {"http://www.skillith.cn", "https://www.skillith.cn", "http://skillith.cn", "https://skillith.cn", "http://localhost:3000", "http://localhost:8080"}, 
             allowCredentials = "true")
public class ContactController {
    
    @Autowired
    private ContactService contactService;
    
    @Autowired
    private SecurityService securityService;
     
    @PostMapping("/contact")
    public ResponseEntity<Map<String, Object>> submitContact(@RequestBody Map<String, String> request, 
                                                           HttpServletRequest httpRequest) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String name = request.get("name");
            String email = request.get("email");
            String phone = request.get("phone");
            String message = request.get("message");
            
            // 获取客户端IP
            String ipAddress = getClientIpAddress(httpRequest);
            
            // 安全检查
            if (securityService.isIpBlacklisted(ipAddress)) {
                response.put("success", false);
                response.put("error", "访问被拒绝");
                return ResponseEntity.status(403).body(response);
            }
            
            if (securityService.isSuspiciousRequest(ipAddress, httpRequest.getHeader("User-Agent"))) {
                response.put("success", false);
                response.put("error", "请求过于频繁，请稍后再试");
                return ResponseEntity.status(429).body(response);
            }
            
            // 验证表单数据
            String validationError = securityService.validateContactForm(name, email, phone, message);
            if (validationError != null) {
                response.put("success", false);
                response.put("error", validationError);
                return ResponseEntity.badRequest().body(response);
            }
            
            // 清理输入内容
            name = securityService.sanitizeInput(name);
            email = securityService.sanitizeInput(email);
            phone = securityService.sanitizeInput(phone);
            message = securityService.sanitizeInput(message);
            
            // 生成设备指纹
            String userAgent = httpRequest.getHeader("User-Agent");
            String acceptLanguage = httpRequest.getHeader("Accept-Language");
            String acceptEncoding = httpRequest.getHeader("Accept-Encoding");
            
            String deviceFingerprint = contactService.generateDeviceFingerprint(
                ipAddress, userAgent, acceptLanguage, acceptEncoding);
            
            // 创建联系消息对象
            ContactMessage contactMessage = new ContactMessage(
                name, email, phone, message, ipAddress, userAgent, deviceFingerprint);
            
            // 提交消息
            boolean success = contactService.submitMessage(contactMessage);
            
            if (success) {
                response.put("success", true);
                response.put("message", "消息发送成功");
            } else {
                response.put("success", false);
                response.put("error", "今日发送次数已达上限");
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("error", "服务器内部错误");
            e.printStackTrace();
        }
        
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/admin/messages")
    public ResponseEntity<Map<String, Object>> getMessages(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(defaultValue = "all") String status) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            Page<ContactMessage> messagePage = contactService.getMessages(page, size, status);
            long totalCount = contactService.getMessageCount(status);
            
            response.put("messages", messagePage.getContent());
            response.put("totalCount", totalCount);
            response.put("currentPage", page + 1);
            response.put("totalPages", messagePage.getTotalPages());
            response.put("hasNext", messagePage.hasNext());
            response.put("hasPrevious", messagePage.hasPrevious());
            
        } catch (Exception e) {
            response.put("error", "获取消息失败");
            e.printStackTrace();
        }
        
        return ResponseEntity.ok(response);
    }
    
    @PutMapping("/admin/messages/{id}")
    public ResponseEntity<Map<String, Object>> updateMessageStatus(
            @PathVariable Long id,
            @RequestBody Map<String, String> request) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String status = request.get("status");
            String adminNotes = request.get("adminNotes");
            
            contactService.updateMessageStatus(id, status, adminNotes);
            response.put("success", true);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("error", "更新失败");
            e.printStackTrace();
        }
        
        return ResponseEntity.ok(response);
    }
    
    @PostMapping("/admin/block-device")
    public ResponseEntity<Map<String, Object>> blockDevice(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String deviceFingerprint = (String) request.get("deviceFingerprint");
            Integer hours = (Integer) request.getOrDefault("hours", 24);
            
            contactService.blockDevice(deviceFingerprint, hours);
            response.put("success", true);
            response.put("message", "设备已封禁 " + hours + " 小时");
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("error", "封禁失败");
            e.printStackTrace();
        }
        
        return ResponseEntity.ok(response);
    }
    
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
            return xForwardedFor.split(",")[0].trim();
        }
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty()) {
            return xRealIp;
        }
        return request.getRemoteAddr();
    }
}
